/////////////////////////////////////////////////////////////////////////////
/// @file -- server_main.cpp
/// @author -- Benjamin Orr
/// @date -- 11.13.11
/// @course -- CS 284
/// @section -- A
/// @assignment -- 3
/// @brief -- The main and supporting functions for a threaded chat server
///////////////////////////////////////////////////////////////////////////////


/////////////////////////////
/// CUSTOM LIBS
/////////////////////////////
#include "../lib/string_manipulation.h"
#include "server_object.h"

/////////////////////////////
/// LIBS
/////////////////////////////
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
#include <signal.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>

//////////////////////////////
/// CONSTS
//////////////////////////////
const unsigned int DEFAULT_CLIENTS = 10;
const unsigned int DEFAULT_PORT = 7744;

//////////////////////////////
/// MAIN
//////////////////////////////
int main(int argc, char * argv[])
{
  //from input arguments
  int port_num, clients;
  port_num = DEFAULT_PORT;

  //Parse input arguments
  //Valid condition, continue
  if(argc == 1)
  {
    cout << "No arguments provided... OK" << endl;
    cout << "Chat server starting on port " << DEFAULT_PORT << "... OK" << endl;
    cout << "Accepting " << DEFAULT_CLIENTS << " chat client connections... OK" << endl << endl;
  }
  //Valid condition, continue
  else if(argc == 3 && 
          str_to_int(charstar_to_str(argv[1])) >= 1024 && 
          str_to_int(charstar_to_str(argv[1])) <= 65535) 
  {
    port_num = str_to_int(charstar_to_str(argv[1]));
    clients  = str_to_int(charstar_to_str(argv[2]));
    cout << "Chat server starting on port " << argv[1] << "... OK" << endl;
    cout << "Accepting " << argv[2] << " chat client connections... OK" << endl << endl;
  }
  //Error condition, return 1
  else
  {
    cout << "Invalid arguments provided. Accepted format:" << endl;
    cout << argv[0] << " <portnumber> <allowableclients>" << endl;
    cout << "<portnumber> must be between 1024 and 65535 or 0 for default" << endl;
    return 1;
  }

  Server server1;
  server1.init(port_num);
  server1.run();
  
  


  return 0;
}
